package com.songcan.basics.core.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.songcan.basics.core.mapper.AreaMapper;
import com.songcan.basics.core.service.AreaService;
import com.songcan.model.basics.Area;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Objects;

@Service
@Slf4j
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements AreaService {

    @Override
    public void addArea(String name, Long pid, String remark, String iconPath, String shortName, String mergerName, String initial, String pinyin, BigDecimal lng, BigDecimal lat) {
        DecimalFormat decimalFormat = new DecimalFormat("0000");
        String levelCode = "";
        Area area1 = null;
        if(Objects.nonNull(pid)){
            int childCount = count(Wrappers.lambdaQuery(new Area())
                    .eq(Area::getPid,pid).eq(Area::getStatus,1));
            Area  area = getById(pid);
            if(childCount > 0){
                levelCode = area.getLevelCode() +"-"+ decimalFormat.format(childCount);

            }else{
                levelCode = area.getLevelCode()+"-"+"0001";
            }
        }else{
            area1 = getOne(Wrappers.lambdaQuery(new Area()).isNull(Area::getPid).orderByDesc(Area::getCreateTime).last(" limit 1"));
            if(Objects.isNull(area1)){
                levelCode = "0000";
            }else {
                levelCode = area1.getLevelCode();
            }
        }
        String[] level = levelCode.split("-");
        while (count(Wrappers.lambdaQuery(new Area()).eq(Area::getLevelCode,levelCode))>0){

            Long code = Long.valueOf(level[level.length-1]);
            code++;
            level[level.length-1] = String.valueOf(decimalFormat.format(code));
            levelCode = StringUtils.join(level,"-");
        }
        area1 = new Area(IdWorker.getId(),name,levelCode,shortName,mergerName,initial,pinyin,lng,lat,new Date(),pid,1);
        save(area1);
    }



}
